import { parse } from 'qs'
import { message } from 'antd'
import { isEmpty, cloneDeep } from 'lodash'
import {
	updateStatus,
	batchDelete,
	batchUpdate,
	checkDelete
} from './roleListServ'

// 初始默认状态
const defaultState = {
	biz: {
		queryForm: {}
	},
	// 弹出框操作类型 -- delete：批量删除；forbid：批量禁用；open：批量启用
	modalType: '',
	// 弹出框显示状态
	showDetailModal: false,
	// 保存操作状态
	btnLoading: false,
	deleteTips: '',
	deleteId: '',
};

const roleListModel = {
	state: cloneDeep(defaultState),
	//订阅数据
	subscriptions: {
		setup({ dispatch, history }) {
			return history.listen(location => {
				if (roleListModel.pathname === '' + location.pathname) {
					dispatch({ type: 'updateStore', payload: cloneDeep(defaultState) });
				}
			})
		},
	},
	//数据逻辑部分
	effects: {
		// 设置表单的值到状态机
		*setFormVal({ payload }, { put, call, select }) {
			let { biz } = yield select(d => d[roleListModel.namespace])
			try {
				yield put({
					type: 'updateStore',
					payload: {
						biz: payload
					}
				})
			} catch (e) {
				console.error(e)
			}
		},

		//启用禁用
		*changeStatus({ payload }, { put, call, select }) {
			try {
				let { data, resultCode } = yield call(updateStatus, payload.params);
				if (resultCode == 0) {
					message.success('操作成功');
					payload.cb();
				}
			} catch (e) {
				console.error(e)
			}
		},

		//批量删除
		*batchDelete({ payload }, { put, call, select }) {
			yield put({ type: 'updateStore', payload: { btnLoading: true } });

			try {
				let { data, resultCode } = yield call(batchDelete, payload.params);
				if (resultCode == 0) {
					message.success('操作成功');
					yield put({ type: 'updateStore', payload: { showDetailModal: false } });
					payload.cb();
				}
			} catch (e) {
				console.error(e)
			}

			yield put({ type: 'updateStore', payload: { btnLoading: false } });
		},

		//批量更新状态
		*batchUpdate({ payload }, { put, call, select }) {
			yield put({ type: 'updateStore', payload: { btnLoading: true } });

			try {
				let { data, resultCode } = yield call(batchUpdate, payload.params);
				if (resultCode == 0) {
					message.success('操作成功');
					yield put({ type: 'updateStore', payload: { showDetailModal: false } });
					payload.cb();
				}
			} catch (e) {
				console.error(e)
			}

			yield put({ type: 'updateStore', payload: { btnLoading: false } });
		},

		//删除校验
		*checkDelete({ payload = {} }, { put, call, select }) {
			try {
				let { data, resultCode, resultMsg } = yield call(checkDelete, payload.params);
				if (resultCode == 0) {
					payload.callback(payload.params.id, resultMsg);
				}
			} catch (e) {
				console.error(e)
			}
		},

	},
	//更新数据到state
	reducers: {
		updateStore(preState, action) {
			return Object.assign({}, preState, action.payload);
		}
	}
}
export default roleListModel
